package com.exam.service.impl;

import com.exam.mapper.LoginUserMapper;
import com.exam.mapper.StudentMapper;
import com.exam.mapper.TeacherMapper;
import com.exam.pojo.ExamMessage;
import com.exam.pojo.LoginUser;
import com.exam.pojo.Student;
import com.exam.pojo.Teacher;
import com.exam.service.LoginService;
import com.exam.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private TeacherMapper teacherMapper;
    @Resource
    private LoginUserMapper loginUserMapper;

    @Override
    public Student queryById(Integer id) {
        return studentMapper.queryById(id);
    }

    @Override
    public int updateById(Student student) {
        return studentMapper.updateById(student);
    }

    @Override
    public PageInfo<Student> queryStuByTeaId(Integer teacherId, int pageNum, int pageSize) {
        Teacher teacher = teacherMapper.queryById(teacherId);
        PageHelper.startPage(pageNum,pageSize);
        List<Student> students = studentMapper.queryStuByInstitute(teacher.getInstitute());
        PageInfo<Student> pageInfo = new PageInfo<>(students);
        return pageInfo;
    }

    @Override
    public PageInfo<Student> queryAllPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Student> students = studentMapper.queryAll();
        PageInfo<Student> pageInfo = new PageInfo<>(students);
        return pageInfo;
    }

    @Override
    public Boolean deleteByUserId(Integer userId) {
        int count = loginUserMapper.deleteById(userId);
        if (count == 0) return false;
        return true;
    }

    @Override
    public List<Integer> queryStuId() {
        return studentMapper.queryStuIdAll();
    }

    @Override
    @Transactional
    public void insert(Student student) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(String.valueOf(student.getStudentId()));
        loginUser.setPassword("123456");
        loginUser.setRole("2");
        int count = loginUserMapper.insert(loginUser);
        if (count == 0) throw new RuntimeException("登录信息添加失败");
        student.setUserId(loginUser.getId());
        int insert = studentMapper.insert(student);
        if (insert == 0) throw new RuntimeException("学生信息添加失败");
    }

}
